/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO.Login;

import DAO.Usuario.HibernateUtil;
import Model.User;
import com.google.gson.Gson;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.hibernate.Session;

/**
 *
 * @author Pedro
 */
@Path("/login")
public class Login {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public Response sayHello(User login) {

        Gson gson = new Gson();
        Session session = null;
        String response = null;

        try {
            session=HibernateUtil.getSession();
            HibernateUtil.beginTransaction();
            List<User> result = session.createQuery("From User WHERE email=? AND senha=? ")
                    .setString(0, login.getEmail())
                    .setString(1, login.getSenha())
                    .list();
            HibernateUtil.commitTransaction();

            if (result.isEmpty() == false) {
                response = gson.toJson(result);
            } else {
                response = "Fail";
            }
        } catch (Exception e) {
            response = "Error";

            session.getTransaction().rollback();
        } finally {
            HibernateUtil.closeSession();
            return Response.status(201).entity(response).build();
        }
    }
}
